﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IMeem.BO;
using System.ComponentModel;
using System.Xml.Linq;

namespace IMeem.API
{
    public class IMeem
    {
        private int _currentPage = 1;
        private string _keyword;
        public delegate void SearchAsyncCompletedHandler(List<SearchResult> results);
        public delegate void SearchAsyncStartedHandler(string keyword);
        public event SearchAsyncCompletedHandler SearchAsyncCompleted;
        public event SearchAsyncStartedHandler SearchAsyncStarted;

        public void SearchAsync(string song, bool isNewSearch)
        {
            BackgroundWorker bw = new BackgroundWorker();
            bw.DoWork += new DoWorkEventHandler(delegate(object sender, DoWorkEventArgs e)
                {
                    List<SearchResult> results = Search(song, isNewSearch);
                    e.Result = results;
                });
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object sender, RunWorkerCompletedEventArgs e)
                {
                    if (e.Error == null)
                    {
                        if (SearchAsyncCompleted != null)
                        {
                            SearchAsyncCompleted(e.Result as List<SearchResult>);
                        }
                    }
                    else
                    {
                        throw new Exception("Error on search", e.Error);
                    }
                });
            bw.RunWorkerAsync();
            if (SearchAsyncStarted != null)
                SearchAsyncStarted(song);
        }        

        public List<SearchResult> Search(string song, bool isNewSearch)
        {
            if (isNewSearch)
                _currentPage = 1; 

            _keyword = song;
            List<SearchResult> results = new List<SearchResult>();
            PageCrawler pageCrawler = new PageCrawler() { Url = string.Format("http://www.imeem.com/tag/{0}/music/?p={1}", song,_currentPage) };
            List<string> blocks = pageCrawler.GetResultsHTMLBlocks();
            foreach (string block in blocks)
            {
                XDocument doc = XDocument.Parse(block);
                SearchResult result = new SearchResult();
                var divs = doc.Root.Descendants("div");
                foreach (XElement div in divs)
                {
                    foreach (XAttribute attrib in div.Attributes())
                    {
                        if (attrib.Value == "Title")
                        {
                            var descendants = div.Descendants("a");
                            foreach (XElement element in descendants)
                            {
                                result.Url = element.Attribute("href").Value;
                                result.Title = element.Value.Trim();                                    
                            }
                        }

                        if (attrib.Value == "Duration")
                        {
                            string duration = div.Value.Trim();
                            int startIndex = duration.IndexOf("(");
                            if (startIndex != -1)
                            {
                                duration = duration.Remove(0, startIndex + 1);
                            }
                            int endIndex = duration.IndexOf(")");
                            if (endIndex != -1)
                            {
                                duration = duration.Remove(endIndex);                            
                            }

                            result.Duration = duration;
                            
                        }

                        if (attrib.Value == "Artist")
                        {
                            result.Artist = div.Value.Trim().Replace("by ","");
                        }
                    }
                }
                results.Add(result);
            }

            return results;
        }

        public void NextResults()
        {
            _currentPage++;
            SearchAsync(_keyword, false);
        }

        public void PreviousResults()
        {
            if (_currentPage > 1)
            {
                _currentPage--;
                SearchAsync(_keyword, false);
            }
        }


        public SearchResult UpdateFlashvars(SearchResult searchResult)
        {
            PageCrawler pageCrawler = new PageCrawler() { Url = searchResult.Url };
            searchResult.Flashvars = pageCrawler.GetFlashvars();
            return searchResult;
        }
    }
}
